package com.jingdianjichi.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.application.convert.AuthUserDTOConverter;
import com.jingdianjichi.auth.entity.AuthUserDTO;
import com.jingdianjichi.auth.entity.Result;
import com.jingdianjichi.auth.domain.entity.AuthUserBO;
import com.jingdianjichi.auth.domain.service.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO){
         try {
             if (log.isInfoEnabled()){
                 log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
             }

             //参数校验
             Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能是空的");
             Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"邮箱地址不能是空的");
             Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能是空的");

             AuthUserBO authUserBO= AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

             Boolean result=authUserDomainService.register(authUserBO);

             return Result.ok(result);

         }catch (Exception e){
            log.error("UserController.register.error:{}",e.getMessage(),e);

            return Result.fail("用户注册失败");
         }
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO){
        try {
            if (log.isInfoEnabled()){
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }

            //参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能是空的");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"邮箱地址不能是空的");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能是空的");

            AuthUserBO authUserBO= AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            Boolean result=authUserDomainService.update(authUserBO);

            return Result.ok(result);

        }catch (Exception e){
            log.error("UserController.update.error:{}",e.getMessage(),e);

            return Result.fail("用户修改失败");
        }
    }

    /**
     * 删除用户信息
     */
    @RequestMapping("/delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO){
        try {
            if (log.isInfoEnabled()){
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDTO));
            }

            AuthUserBO authUserBO= AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            Boolean result=authUserDomainService.delete(authUserBO);

            return Result.ok(result);

        }catch (Exception e){
            log.error("UserController.delete.error:{}",e.getMessage(),e);

            return Result.fail("用户删除失败");
        }
    }

    /**
     * 用户的启用和禁用
     */
    @RequestMapping("/changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO){
        try {
            if (log.isInfoEnabled()){
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
            }

            Preconditions.checkNotNull(authUserDTO.getStatus(),"用户状态不能是空的");

            AuthUserBO authUserBO= AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            Boolean result=authUserDomainService.update(authUserBO);

            return Result.ok(result);

        }catch (Exception e){
            log.error("UserController.changeStatus.error:{}",e.getMessage(),e);

            return Result.fail("用户状态修改失败");
        }
    }


    /**
     * 用户注册,参数就是验证码
     */
    @RequestMapping("/doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode){
        try {
            if (log.isInfoEnabled()){
                log.info("UserController.doLogin.validCode:{}", JSON.toJSONString(validCode));
            }
            //我们根据验证码找对应的OpenID
            Preconditions.checkArgument(!StringUtils.isBlank(validCode),"验证码不能是空的");

            //注册
            SaTokenInfo tokenInfo=authUserDomainService.doLogin(validCode);

            return Result.ok(tokenInfo);
        }catch (Exception e){
            log.error("UserController.doLogin.error:{}",e.getMessage(),e);

            return Result.fail("用户注册失败");
        }

    }


    /**
     * 用户注册,参数就是验证码
     */
    @RequestMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO){
        try {
            if (log.isInfoEnabled()){
                log.info("UserController.doLogin.getUSerInfo:{}", JSON.toJSONString(authUserDTO));
            }

            //我们根据验证码找对应的OpenID,我们就校验userName就行了
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能是空的");

            AuthUserBO authUserBO= AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            //注册
            AuthUserBO authUserBOResult=authUserDomainService.getUSerInfo(authUserBO);

            AuthUserDTO authUserDT0Result = AuthUserDTOConverter.INSTANCE.convertBOToDTO(authUserBOResult);

            return Result.ok(authUserDT0Result);
        }catch (Exception e){
            log.error("UserController.getUSerInfo.error:{}",e.getMessage(),e);

            return Result.fail("用户查询失败");
        }
    }

    /**
     * 用户退出,只会把token删除的,不会把Redis中个用户权限删除的所以可以直接在Redis中查的
     */
    @RequestMapping("/logOut")
    public Result logout(@RequestParam String userName) {
        try {
            //我们如果不是对象的话是不用序列化的,而且不用+判断,因为不是对象不会去序列化
            log.info("UserController.logout.getUSerInfo:{}",userName);


            //我们根据验证码找对应的OpenID,我们就校验userName就行了
            Preconditions.checkArgument(!StringUtils.isBlank(userName),"用户名不能是空的");

            StpUtil.logout(userName);

            return Result.ok();
        }catch (Exception e){
            log.error("UserController.logout.error:{}",e.getMessage(),e);

            return Result.fail("用户退出失败");
        }
    }


    /**
     * 批量获取用户信息
     */
    @RequestMapping("listByIds")
    public Result<List<AuthUserDTO>> listUserInfoByIds(@RequestBody List<String> userNameList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.listUserInfoByIds.dto:{}", JSON.toJSONString(userNameList));
            }

            //校验
            Preconditions.checkArgument(!CollectionUtils.isEmpty(userNameList), "id集合不能为空");

            List<AuthUserBO> userInfos = authUserDomainService.listUserInfoByIds(userNameList);

            return Result.ok(AuthUserDTOConverter.INSTANCE.convertBOToDTO(userInfos));
        } catch (Exception e) {
            log.error("UserController.listUserInfoByIds.error:{}", e.getMessage(), e);
            return Result.fail("批量获取用户信息失败");
        }
    }

}
